package com.weixin.program.utils;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年03⽉11⽇<br/>
 * @version：v1.0.0<br>
 */
@Slf4j
public class HtmlUtil {

    private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 在HTML指定位置新增标签
     *
     * @param imagepath
     * @param htmlContent
     * @return
     * @throws IOException
     */
    public static String buildHtml(String htmlContent, String imagepath) throws IOException {
        Document doc = Jsoup.parse(htmlContent);
        Elements rows = doc.select("table[class=emailList]").get(0).select("tr");
        if (rows.size() == 0) {
            log.error("获取到table[class=emailList]标签为空");
        } else {
            String date = LocalDate.now().format(fmt);
            imagepath = imagepath + date + ".png";
            String imgBase64 = Base64Util.GetImageStr(imagepath);
            Element row = rows.get(1);
            row.after("<tr>\n" +
                    "    <td>\n" +
                    "        <div>\n" +
                    "            <img src=\"data:image/png;base64," + imgBase64 + "\">\n" +
                    "        </div>\n" +
                    "    </td>\n" +
                    "</tr>");
            return doc.toString();
        }
        return htmlContent;
    }
}
